package com.kantboot.io.controller;

import com.kantboot.io.TO.JoinTO;
import com.kantboot.io.entity.CesUser;
import com.kantboot.io.mapper.CesSessionMapper;
import com.kantboot.io.service.CesUserService;
import com.kantboot.io.util.RestResult;
import com.kantboot.io.util.SessionUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/ces-user")
@CrossOrigin(origins = "*",maxAge = 3600)
public class CesUserController {

    @Resource
    SessionUtil sessionUtil;

    @Resource
    CesUserService cesUserService;

    /**
     * 登录
     * @param username 账号
     * @param password 密码
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public RestResult<String> login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request
    ){
        CesUser cesUser = cesUserService.login(username, password);
        sessionUtil.setCesUser(cesUser,request);
        return RestResult.success("登录成功","登录成功");
    }

    /**
     * 注册
     * @param joinTO
     * @return
     */
    @RequestMapping("/join")
    public RestResult<String> join(JoinTO joinTO){
        cesUserService.join(joinTO);
        return RestResult.success("注册成功","注册成功");
    }

    /**
     * 根据Session获取用户
     */
    @RequestMapping("/get_user_info")
    public RestResult<CesUser> getUserInfo(HttpServletRequest request){
        return RestResult.success(
                sessionUtil.getCesUser(request)
                    .setPassword(null)
                    .setSalt(null)
                ,"获取成功");
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @RequestMapping("/quit_login")
    public RestResult<String> quitLogin(HttpServletRequest request){
        sessionUtil.deleteBySession(request);
        return  RestResult.success("退出成功","退出成功");
    }
}
